import {Form, Modal, Row, Col, Input} from 'antd';
import {useEffect} from 'react';
import {connect} from 'umi';

const ResetPassForm = (props) => {
  const {dispatch, submitting} = props;
  const {resetPassForm, setResetPassForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });
      dispatch({
        type: 'PSystemUser/resetPass',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setResetPassForm(undefined);
    form.resetFields();
  }

  /* 初始化表单数据 */
  useEffect(() => {
    if (resetPassForm && resetPassForm.data) {
      form.setFieldsValue({...resetPassForm.data});
    }
  }, [resetPassForm, form]);

  return (
    <Modal
      confirmLoading={submitting}
      title={resetPassForm ? resetPassForm.title : ''}
      open={resetPassForm ? resetPassForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={600}
      bodyStyle={{paddingTop: 24}}
    >
      <Form layout='horizontal' labelCol={{span: 5}} form={form}>
        {resetPassForm && resetPassForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='newPass' label='新的密码'
              rules={[
                {required: true, message: '新的密码不能为空'},
              ]}>
              <Input.Password placeholder='请输入新的密码'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='againPass' label='再次密码'
              rules={[
                {required: true, message: '再次密码不能为空'},
              ]}>
              <Input.Password placeholder='请输入再次密码'/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};


export default connect(({loading}) => {
  return {
    submitting: loading.effects['PSystemUser/resetPass'],
  };
})(ResetPassForm);

